package com;

/**
 * Created with IntelliJ IDEA.
 * Description:判断一个链表是否为回文结构
 * User: YJ
 * Date: 2024-3-09
 * Time: 21:44
 */
class ListNode {
    int val;
    ListNode next = null;

    public ListNode(int val) {
        this.val = val;
    }
}

public class isPail {
    //将链表逆序
    public static ListNode reverse(ListNode head) {
        ListNode pre = new ListNode(-1);
        ListNode cur = head;
        while(cur != null) {
            ListNode tmp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = tmp;
        }
        return pre;
    }
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     *
     * @param head ListNode类 the head
     * @return bool布尔型
     */
    public static boolean isPail(ListNode head) {
        // write code here
        if(head.next == null ) {
            return true;
        }
        //复制一个链表，将该链表逆序
        ListNode list2 = new ListNode(-1);
        ListNode pre = list2;
        ListNode cur = head;
        while (cur != null) {
            ListNode l = new ListNode(cur.val);
            list2.next = l;
            list2 = list2.next;
            cur = cur.next;
        }
        ListNode head2 = reverse(pre.next);
        //比较两个链表的值
        while(head != null && head2 != null) {
            if(head.val != head2.val) {
                return false;
            }
            head = head.next;
            head2 = head2.next;
        }
        return true;
    }

    //测试
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        ListNode list1 = new ListNode(2);
        ListNode list2 = new ListNode(3);
        ListNode list3 = new ListNode(2);
        ListNode list4 = new ListNode(1);
        head.next = list1;
        list1.next = list2;
        list2.next = list3;
        list3.next = list4;
        System.out.println(isPail(head));
    }
}
